const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const { query } = require('../config/db');

// 配置文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadDir = path.join(__dirname, '../../public/uploads/');
        // 确保上传目录存在
        require('fs').mkdirSync(uploadDir, { recursive: true });
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 5 * 1024 * 1024 // 限制5MB
    },
    fileFilter: function (req, file, cb) {
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (allowedTypes.includes(file.mimetype)) {
            cb(null, true);
        } else {
            cb(new Error('不支持的文件类型！'));
        }
    }
});

// 添加商品到购物车
router.post('/add', upload.single('image'), (req, res) => {
    const { title, content, price } = req.body;
    const image = req.file ? `/uploads/${req.file.filename}` : '';

    // 数据验证
    if (!title || !content || !price) {
        return res.status(400).json({
            code: 400,
            message: '缺少必要参数'
        });
    }

    const sql = 'INSERT INTO cart (title, content, image, price,detail) VALUES (?, ?, ?, ?,?)';
    const params = [title, content, image, price,detail];

    query(sql, params, (err, results) => {
        if (err) {
            console.error('添加购物车失败：', err);
            return res.status(500).json({
                code: 500,
                message: '服务器错误'
            });
        }

        res.json({
            code: 200,
            message: '添加成功',
            data: {
                id: results.insertId,
                title,
                content,
                image,
                price
            }
        });
    });
});


// 获取购物车列表
router.post('/list', (req, res) => {
    const sql = 'select * from cart';
    query(sql, [], (err, result) => {
        if (err) {
            res.send({
                success: "失败",
                msg: "false",
                err: err.message
            });
        } else {
            res.send({
                success: "成功",
                msg: "true",
                result: result
            });
        }
    });
});

// 删除购物车商品
router.post('/delete', (req, res) => {
    const sql = 'DELETE FROM cart where id=?';
    query(sql, [req.body.id], (err, result) => {
        if (err) {
            res.send({
                success: "失败",
                msg: "false",
                err: err.message
            });
        } else {
            res.send({
                success: "成功",
                msg: "true",
                result: result
            });
        }
    });
});

// 更新购物车商品
router.post('/update', (req, res) => {
    const sql = 'UPDATE cart SET title=?, content=?, image=?, price=? WHERE id=?';
    query(sql, [req.body.title, req.body.content, req.body.image, req.body.price, req.body.id], (err, result) => {
        if (err) {
            res.send({
                success: "失败",
                msg: "false",
                err: err.message
            });
        } else {
            res.send({
                success: "成功",
                msg: "true",
                result: result
            });
        }
    });
});
module.exports = router;